package com.example.demo.socket;

import com.example.demo.http.Request;
import com.example.demo.http.Response;
import com.example.demo.servlet.HttpMeServlet;

import java.io.OutputStream;
import java.net.Socket;

/**
 * 使用线程处理
 *
 * @author maxf
 * @version 1.0
 * @ClassName SP
 * @Description
 * @date 2019/2/13 15:53
 */
public class SocketProcess extends Thread {
    protected Socket socket;

    /**
     * 构造方法
     *
     * @param socket
     */
    public SocketProcess(Socket socket) {
        this.socket = socket;
    }

    /**
     * run
     */
    @Override
    public void run() {
        try {
            Request request = new Request(socket.getInputStream());
            Response response = new Response(socket.getOutputStream());
            //需要进行处理的 拿到url指定的Servlet实例
            HttpMeServlet httpMeServlet = MyTomcat.ServletHashMap.get(request.getUrl().replace("/", ""));
            //判断是否为空
            if (null != httpMeServlet) {
                httpMeServlet.service(request, response);
            } else {
                OutputStream outputStream = response.out;
                String s = Response.heard + "404:not fund servlet";
                outputStream.write(s.getBytes());
                outputStream.flush();
                outputStream.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //socket必须关闭
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
